import {createVNode, defineComponent,render,reactive} from 'vue';
import {ElButton, ElDialog, ElInput} from "element-plus";

const DialogComponent = defineComponent({
  props:{
    option: {type: Object}
  },
  setup(props,ctx) {
    console.log('props.option:',props.option);
    const state = reactive({
      visible: false,
      option: props.option
    });

    //组件会暴露以下方法
    ctx.expose({
      showDialog(option){
        state.option = option;
        state.visible = true;
      }
    });

    const onCancel = () => {
      state.visible = false;
    };

    const onConfirm = () => {
      state.visible = true;
      state.option.onConfirm && state.option.onConfirm(state.option.content);
      state.visible = false;
    };

    return () => {
      return <ElDialog v-model={state.visible} title={state.option.title}>
        {{
          default:()=> <ElInput
            type='textarea'
            v-model={state.option.content}
            rows={10}
          />,
          footer: () => state.option.footer
            && <div>
              <ElButton onClick={onCancel}>取消</ElButton>
              <ElButton type='primary' onClick={onConfirm}>确定</ElButton>
            </div>
        }}
      </ElDialog>
    }
  }
});

let componentVNode;
export function $dialog(option) {
  if(!componentVNode){
    //step1
    const el = document.createElement('div');
    //step2
    componentVNode = createVNode(DialogComponent, {option});
    //step3
    render(componentVNode, el); //此时componentVNode的component属性就有值了
    //使用vue 要想自己手动渲染一个虚拟节点, 就必须经过以上三步, 之所以有第一步, 是因为vue提供的render函数必须要接受一个el
    //render还能提供diff的能力
    document.body.appendChild(
      el
    );
  }
  //↑不用关心怎么关闭隐藏弹窗 因为ElDialog已经帮我们做了 只需要点击mask即可隐藏弹窗

  const {showDialog} = componentVNode.component.exposed;
  showDialog(option);
}

